$(function(){

    var isEdit = Number(getParamsByUrl(location.href,'isEdit'));
    if(isEdit){
        if(localStorage.getItem("editAddress")){
            var address = JSON.parse(localStorage.getItem("editAddress"));
            console.log(address);
            var html = template("editTpl",address);
            $("#edit-box").html(html);
            $(".mui-title").text("编辑收货地址");
        };
    }else {
        var html = template("editTpl",{});
        $("#edit-box").html(html);
    };

        var picker = new mui.PopPicker({layer:3});
        picker.setData(cityData);
    $("#selectCity").on("tap",function(){
        picker.show(function(selectItems){
            $('#selectCity').val(selectItems[0].text + 
                selectItems[1].text +
                selectItems[2].text)
        });
    });


    $("#confirm").on("click",function(){
        var username = $("[name='username']").val();
        var postcode = $("[name='postcode']").val();
        var city = $("[name='city']").val();
        var detail = $("[name='detail']").val();

        if(!username){
            mui.toast("请输入收货人姓名");
            return;
        }
        if(!postcode){
            mui.toast("请输入邮政编码");
            return;
        }
        if(!city){
            mui.toast("请输入省市区");
            return;
        }
        if(!detail){
            mui.toast("请输入详细地址");
            return;
        }

        var data = {
            address : city,
            addressDetail : detail,
            recipients : username,
            postcode : postcode
        };

        var url = null;
        var text = "";
        if(isEdit){
            url = "/address/updateAddress";
            data.id  = address.id;
            text = "修改收货地址";

        }else{
            url = "/address/addAddress";
            text = "添加收货地址";
        }
        
        $.ajax({
            type: "post",
            url: url,
            data: data,
            success: function (res) {
                if(res.success){
                    mui.toast("修改成功");
                    location.href = "address.html";
                }else {
                    mui.toast("修改失败");
                }
            }
        });
    });
});